import React from 'react';
import {BackHandler, Platform} from 'react-native';
import {createBottomTabNavigator} from '@react-navigation/bottom-tabs';
import Home from '../pages/Home';
import Samples from '../pages/Samples';
import Mine from '../pages/Mine';
import IconHome from '../assets/icons/Home';
import IconSamples from '../assets/icons/Samples';
import IconMine from '../assets/icons/Mine';
import useBackHandler from '../hooks/useBackHandler';
import {useNavigation} from '@react-navigation/native';
import {showToast} from '../utils/common';

const IndexTabs = () => {
  const Tab = createBottomTabNavigator();
  const navigation = useNavigation();

  /// Android物理返回键处理
  let lastBackPressed = 0;
  let thisBackPressed = 0;
  const onBackAndroid = () => {
    if (!navigation.canGoBack()) {
      let time = new Date();
      lastBackPressed = thisBackPressed;
      thisBackPressed = time.getTime();
      if (lastBackPressed && lastBackPressed + 2000 >= thisBackPressed) {
        //最近2秒内按过back键，可以退出应用。
        BackHandler.exitApp();
        return false;
      }
      showToast('再按一次退出应用！');
      return true;
    }
    return false;
  };
  if (Platform.OS === 'android') {
    useBackHandler(() => onBackAndroid());
  }

  return (
    <Tab.Navigator
      screenOptions={{
        tabBarActiveTintColor: '#ff5700',
        headerTitleAlign: 'center',
        headerTintColor: '#333333',
      }}>
      <Tab.Screen
        name="Home"
        component={Home}
        options={{
          title: '首页',
          tabBarLabel: '首页',
          tabBarIcon: ({color, size}) => <IconHome color={color} size={size} />,
        }}
      />
      <Tab.Screen
        name="Component"
        component={Samples}
        options={{
          title: '示例',
          tabBarLabel: '示例',
          tabBarIcon: ({color, size}) => (
            <IconSamples color={color} size={size} />
          ),
        }}
      />
      <Tab.Screen
        name="Mine"
        component={Mine}
        options={{
          title: '我的',
          tabBarLabel: '我的',
          tabBarIcon: ({color, size}) => <IconMine color={color} size={size} />,
        }}
      />
    </Tab.Navigator>
  );
};

export default IndexTabs;
